/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package business;

import data.Grouptable;
import data.Usertable;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author stana
 */
@SessionScoped
@ManagedBean
public class LoginBean implements Serializable
{

    private String username;
    private String password;
    @EJB
    private business.UsertableFacade userFacade;
    Usertable user;
    private boolean isUserLogged;
    private boolean isAdminLogged;
    @EJB
    private business.GrouptableFacade groupFacade;

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public boolean isIsUserLogged()
    {
        isUserLogged=isLoged("USERS");
        return isUserLogged;
    }

    private boolean isLoged(String group)
    {
        isUserLogged=false;
        Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
        if (principal != null)
        {
            user = userFacade.find(principal.getName()); // Find User by j_username.
            List<Grouptable> groups=groupFacade.findByID(user.getUserid());
            for(Grouptable g:groups)
            {
                if(g.getGrouptablePK().getGroupid().equals(group))
                {
                    isUserLogged=true;
                }
            }
        }
        else
        {
        }
        return isUserLogged;
    }

    public void setIsUserLogged(boolean isUserLogged)
    {
        this.isUserLogged = isUserLogged;
    }

    public boolean isIsAdminLogged()
    {
        isAdminLogged=isLoged("ADMINISTRATORS");
        return isAdminLogged;
    }

    public void setIsAdminLogged(boolean isAdminLogged)
    {
        this.isAdminLogged = isAdminLogged;
    }




    public String login() throws NoSuchAlgorithmException, UnsupportedEncodingException
    {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytesOfMessage = this.password.getBytes("UTF-8");
        byte[] digest = md.digest(bytesOfMessage);

        BigInteger bigInt = new BigInteger(1, digest);
        String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
        while (hashtext.length() < 32)
        {
            hashtext = "0" + hashtext;
        }


        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try
        {
            request.login(this.username, this.password);
            this.user = userFacade.find(this.username, hashtext);
        } catch (ServletException e)
        {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
            return "";
        }
        if(isIsUserLogged())
        {
            return "/pages/user/List";
        }
        return "/index";

    }

    public String logout()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try
        {
            request.logout();
        } catch (ServletException ex)
        {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        user=null;
        isAdminLogged=false;
        isUserLogged=false;
        return "/index";
    }

}
